package com.mall.common.config.security;

import com.mall.common.constants.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xyl
 * @date 2021-02-09 0:41
 */
@Component
public class CaptchaFilter extends GenericFilterBean {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        String defaultFilterProcessUrl = "/login";
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
            // 验证码验证
            String requestCaptcha = request.getParameter("captcha");
            if (StringUtils.isEmpty(requestCaptcha)) {
                throw new AuthenticationServiceException("验证码不能为空!");
            }
            String redisCaptcha = (String) redisTemplate.opsForValue().get(Constants.REDIS_KEY_CAPTCHA_PREFIX+request.getSession().getId());
            if (StringUtils.isEmpty(redisCaptcha)) {
                throw new AuthenticationServiceException("请刷新验证码!");
            }
            if (!redisCaptcha.equalsIgnoreCase(requestCaptcha)) {
                throw new AuthenticationServiceException("验证码错误!");
            }
        }
        chain.doFilter(request, response);
    }
}
